<template>
  <div class="floating-button" ref="button" @click="handleClick" @mousedown="startDrag">
    <i class="add-button-icon"></i>
  </div>
</template>

<script setup>
import { ref, defineProps, onMounted, onUnmounted } from 'vue';

const button = ref(null);
let isDragging = false;
let offsetX = 0;
let offsetY = 0;
let starX = 0;
let starY = 0;
let isClick = false;

//点击事件处理
const receivedProps = defineProps({
  parentRect: Object,
  onClick: Function
});
function handleClick() {
  if (isClick && receivedProps.onClick) {
    receivedProps.onClick();
  }
}

onMounted(() => {
  //初始按钮定位
  button.value.style.left = (receivedProps.parentRect.width - 80) + 'px';
  button.value.style.top = (receivedProps.parentRect.height * 0.33) + 'px';
});

//开始
const startDrag = (event) => {
  isDragging = true;
  isClick = false;
  offsetX = event.clientX - button.value.getBoundingClientRect().left;
  offsetY = event.clientY - button.value.getBoundingClientRect().top;
  starX = button.value.style.left;
  starY = button.value.style.top;
  document.addEventListener('mousemove', onDrag);
  document.addEventListener('mouseup', stopDrag);
};

//停止
const stopDrag = () => {
  isDragging = false;
  if (starX == button.value.style.left && starY == button.value.style.top) {
    isClick = true;
  }
  console.log('button.value.style.left', button.value.style.left)
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
};

//拖动
const onDrag = (event) => {
  if (isDragging) {
    const x = event.clientX - offsetX;
    const y = event.clientY - offsetY;
    // 限制按钮在父组件内移动
    const newLeft = Math.max(receivedProps.parentRect.left, Math.min(receivedProps.parentRect.right - button.value.offsetWidth, x));
    const newTop = Math.max(receivedProps.parentRect.top, Math.min(receivedProps.parentRect.bottom - button.value.offsetHeight, y));

    button.value.style.position = 'absolute';
    button.value.style.left = `${newLeft - receivedProps.parentRect.left}px`;
    button.value.style.top = `${newTop - receivedProps.parentRect.top}px`;
  }
};

// 清理事件监听器
onUnmounted(() => {
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
});
</script>